package com.want.proxy;

import com.want.client.Client;
import com.want.client.WantLoadBalanceClient;
import com.want.method.handler.WantReactorInvocationHandler;
import com.want.service.ServiceInfo;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Proxy;

/**
 * @author WangZhiJian
 * @since 2021/12/4 0004
 */
@Slf4j
public class JDKWantProxyCreator implements  WantProxyCreator {

    private static final WantProxyCreator instance = new JDKWantProxyCreator();

    public static WantProxyCreator getInstance(){
        return instance;
    }

    @Override
    public Object createProxy(Class<?> type, Client client, ServiceInfo serviceInfo) {
        log.info("createProxy: {}", type);
        if(client == null)
            client = new Client.DefaultClient();
        if(client instanceof WantLoadBalanceClient){
            WantLoadBalanceClient wantLoadBalanceClient = WantLoadBalanceClient.from((WantLoadBalanceClient) client);
            wantLoadBalanceClient.setServiceName(serviceInfo.getServiceName());
            client = wantLoadBalanceClient;
        }
        return Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[]{type}, new WantReactorInvocationHandler(client,type,serviceInfo));
    }

}
